package com.beemans.admob.ads;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.ResponseInfo;
import com.google.android.gms.ads.admanager.AdManagerAdRequest;
import com.google.android.gms.ads.admanager.AdManagerAdView;

public class AbBannerAdWrapper {
    @NonNull
    private final AbBannerAdvertConfig advertConfig;
    @Nullable
    private ViewGroup viewGroup;
    @Nullable
    private AdManagerAdView adView;
    @Nullable
    private AbAdNetworkListener networkListener;
    @Nullable
    private AbAdEventListener eventListener;

    private boolean isLoadingAd = false;

    public boolean isAdvertReady() {
        return false;
    }

    public boolean isAdvertLoading() {
        return isLoadingAd;
    }

    public AbBannerAdWrapper(
            @NonNull ViewGroup viewGroup,
            @NonNull AbBannerAdvertConfig advertConfig,
            @NonNull AbAdNetworkListener networkListener,
            @NonNull AbAdEventListener eventListener
    ) {
        this.viewGroup = viewGroup;
        this.advertConfig = advertConfig;
        this.networkListener = networkListener;
        this.eventListener = eventListener;

        initAdvert();
    }

    private void initAdvert() {
        if (viewGroup == null) {
            return;
        }

        final Context context = viewGroup.getContext();

        adView = new AdManagerAdView(context);
        adView.setAdUnitId(advertConfig.getPlacementId());
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                isLoadingAd = false;

                if (networkListener != null) {
                    networkListener.onAdLoaded();
                }
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                isLoadingAd = false;

                if (networkListener != null) {
                    networkListener.onAdFailedToLoad(loadAdError.toString());
                }
            }

            @Override
            public void onAdImpression() {
                if (eventListener != null) {
                    eventListener.onAdImpression(getResponseInfo());
                }
            }

            @Override
            public void onAdClicked() {
                if (eventListener != null) {
                    eventListener.onAdClicked(getResponseInfo());
                }
            }

            @Override
            public void onAdClosed() {
                if (eventListener != null) {
                    eventListener.onAdClosed(getResponseInfo());
                }
            }

            @Override
            public void onAdOpened() {
            }

            @Override
            public void onAdSwipeGestureClicked() {
            }
        });

        if (viewGroup.getVisibility() != View.VISIBLE) {
            viewGroup.setVisibility(View.VISIBLE);
        }

        viewGroup.post(() -> {
            if (adView != null && viewGroup != null) {
                final ViewParent viewParent = adView.getParent();
                if (viewParent instanceof ViewGroup) {
                    ((ViewGroup) viewParent).removeView(adView);
                }

                viewGroup.removeAllViews();
                viewGroup.addView(adView);

                final int advertWidth = viewGroup.getWidth();
                final int adWidthDp = (int) AbAdvertUtils.pxToDp(context, advertWidth);
                adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidthDp));
            }
        });
    }

    public void loadAd() {
        if (viewGroup == null) {
            return;
        }
        viewGroup.post(() -> {
            if (adView == null) {
                return;
            }

            isLoadingAd = true;

            try {
                final AdManagerAdRequest.Builder builder = new AdManagerAdRequest.Builder();
                if (advertConfig.isCollapsible()) {
                    final Bundle bundle = new Bundle();
                    bundle.putString(AbAdvertConstants.BANNER_COLLAPSIBLE, AbAdvertConstants.BANNER_BOTTOM);
                    builder.addNetworkExtrasBundle(AdMobAdapter.class, bundle);
                }
                adView.loadAd(builder.build());
            } catch (Throwable throwable) {
                isLoadingAd = false;

                if (networkListener != null) {
                    networkListener.onAdFailedToLoad(throwable.getMessage());
                }
            }
        });
    }

    public void destroy() {
        networkListener = null;
        eventListener = null;

        if (viewGroup != null) {
            viewGroup.removeAllViews();
            viewGroup = null;
        }
        if (adView != null) {
            final ViewParent viewParent = adView.getParent();
            if (viewParent instanceof ViewGroup) {
                ((ViewGroup) viewParent).removeView(adView);
            }
            try {
                adView.destroy();
            } catch (Throwable ignored) {
            }

            adView = null;
        }
    }

    @Nullable
    private ResponseInfo getResponseInfo() {
        return adView != null ? adView.getResponseInfo() : null;
    }
}